import { think } from "thinkjs";
import Base, { ServiceOption } from "@/service/base";
import { RestModelClass, RestOption } from '@/types/utils/rest';

import { ISnsThread } from '../../types';
import { SnsThreadModelClass } from "../model/thread";
import { IServiceSnsThreadGetParams } from "../../types/service/thread";

/**
 * 主题服务
 */
export class FollowServiceClass extends Base {

  /**
   * 新增或更新
   */
  async put(data: ISnsThread) {
    const auth = await this.checkAuth();
    const threadModel = this.model('sns_thread') as SnsThreadModelClass;
    const isAdd = !data.id;
    try {
      await threadModel.startTrans();
      let option: RestOption<ISnsThread> = {
        tableName: 'sns_thread',
        privateKey: 'id',
        autoCreateUpdateTime: true,
        putFormat: {
          // sku_price: 'jsonStringify'
        },
        // allowEdit: [],
        db: threadModel.db(),
        // rule: RuleCardPut
      };
      const restModel = new RestModelClass(option);
      const id = await restModel.put(data);
      await threadModel.commit();
      return id;
    } catch (e) {
      await threadModel.rollback();
      throw new Err(e);
    }
  }

  async get(params: IServiceSnsThreadGetParams) {
    let auth = await this.checkAuth();
    let option: RestOption<ISnsThread> = {
      tableName: 'sns_thread',
      privateKey: 'id',
      alias: 'gb',
      where: {
        'gb.shop_id': auth.role.shop_id
      },
      queryFormat: {
        create_time: {
          type: 'dateFormatDateTime',
          as: 'start_time_str',
        },
        update_time: {
          type: 'dateFormatDateTime',
          as: 'end_time_str',
        }
      },
    };
    const restModel = new RestModelClass(option);
    let res = await restModel.get(params);
    return res;
  }

  async delete({
    tableName,
    privateKey,
    ...params
  }: any) {
    const auth = await this.checkAuth();
    if (!tableName || !privateKey) throw new Err('缺少参数 tableName | privateKey');
    let option: RestOption<ISnsThread> = {
      tableName,
      privateKey
    };
    const restModel = new RestModelClass(option);
    return restModel.delete(params);
  }

}

export default FollowServiceClass;
